import env from './utils/config.js';
import base64 from './utils/base64.js';
import Crypto from './utils/crypto.js';
import hmac from './utils/hmac.js';
import sha1 from './utils/sha1.js';
import tools from '@/utils/tools.js'

(function() {
	Date.prototype.format = function(fmt) {
		var o = {
			'M+': this.getMonth() + 1, //月份
			'd+': this.getDate(), //日
			'h+': this.getHours(), //小时
			'm+': this.getMinutes(), //分
			's+': this.getSeconds(), //秒
			'q+': Math.floor((this.getMonth() + 3) / 3), //季度
			S: this.getMilliseconds(), //毫秒
		};

		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
		}

		for (var k in o) {
			if (new RegExp('(' + k + ')').test(fmt)) {
				fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k])
					.length));
			}
		}

		return fmt;
	};
}());

function getPolicyBase64() {
	let date = new Date();
	date.setHours(date.getHours() + env.timeout);
	let srcT = date.toISOString();
	const policyText = {
		"expiration": srcT, // Policy失效时间
		"conditions": [
			["content-length-range", 0, 100 * 1024 * 1024] // 设置上传文件的大小限制,100mb
		]
	};

	const policyBase64 = base64.base64.encode(JSON.stringify(policyText));
	return policyBase64;
}

function getSignature(policyBase64) {
	const accesskey = env.AccessKeySecret;
	const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
		asBytes: true
	});
	const signature = Crypto.util.bytesToBase64(bytes);
	return signature;
}

function getFileInfo(file) {
	return new Promise((resolve, reject) => {
		uni.getFileInfo({
			filePath: file,
			success(info) {
				console.log(info, '文件信息');
				resolve(info)
			},
			fail(e) {
				console.error(e);
				toolsMethods.showTips('获取文件信息异常');
			}
		})
	})
}

/*
 * 格式化文件
 *@param - files: 上传文件数据
 *@param - size: 限制的文件大小
 *@param - prefix: 需要添加的前缀
 */

function formatFiles(options) {
	return new Promise((resolve, reject) => {
		let formatTask = [];
		let path = "";
		if (!Array.isArray(options.files)) {
			let taskKeys = Object.keys(options.files);
			let taskValues = Object.values(options.files);
			taskKeys.forEach((item, itemIndex) => {
				formatTask.push(
					taskValues[itemIndex].map((file) => {
						if (options.size && file.size > options.size) reject('文件超出大小限制');
						else {
							path = file?.path ?? file?.tempFilePath ?? file;
							console.log(path, '文件临时路径');
							return {
								url: env.uploadImageUrl,
								filePath: options.prefix ? options.prefix + path :
								path, //因为app平台选择文件可能需要添加 file://前缀 所以需要拼接
								name: file?.name ? file?.name : path.substring(path.lastIndexOf(
									'/') + 1),
								path: path,
								size: file?.size ?? 0,
								source: 0,
							}
						}
					})
				)
			})
		} else {
			options.files.forEach((item, itemIndex) => {
				if (options.size && item?.size > options.size) reject('文件超出大小限制')
				else {
					path = item?.path ?? item?.tempFilePath ?? item;
					console.log(path, '文件临时路径');
					formatTask.push({
						url: env.uploadImageUrl,
						filePath: options.prefix ? options.prefix + path :
						path, //因为app平台选择文件可能需要添加 file://前缀 所以需要拼接
						name: item?.name ? item?.name : path.substring(path.lastIndexOf('/') +
							1),
						path: path,
						size: item?.size ?? 0,
						source: 1,
					})
				}
			})
		}
		resolve(formatTask);
	})
}

function formatGzip(str, gzip) {
	return str.indexOf('?x-oss-process=image/quality,q_') > -1 ? str.substr(0, str.indexOf(
			'?x-oss-process=image/quality,q_')) + `?x-oss-process=image/quality,q_${gzip}` :
		`${str}?x-oss-process=image/quality,q_${gzip}`
}

function uploadFiles(files, options) {
	return new Promise((resolve, reject) => {
		let taskResult = [];
		if (Array.isArray(files)) {
			files.forEach((option) => {
				taskResult.push(
					new Promise((resolve, reject) => {
						if (option.filePath && option.filePath.indexOf(env.uploadImageUrl) === -
							1) {
							uni.uploadFile({
								...option,
								success(res) {
									console.log(res, 'success');
									if (options.method === 'images/' && options.gzip)
										resolve(formatGzip(env.uploadImageUrl + option
											.formData.key, options.gzip))
									else resolve(env.uploadImageUrl + option.formData
										.key)
								},
								fail(err) {
									console.error(err, 'err');
									reject(err)
								}
							});
						} else {
							resolve(option.filePath)
						}
					}))
			})
		} else {
			taskResult.push(
				new Promise((resolve, reject) => {
					if (files.filePath && files.filePath.indexOf(env.uploadImageUrl) === -1) {
						uni.uploadFile({
							...files,
							success(res) {
								if (options.method === 'images/' && options.gzip) resolve(
									formatGzip(env.uploadImageUrl + files.formData.key,
										options.gzip))
								else resolve(env.uploadImageUrl + files.formData.key)
							},
							fail(err) {
								reject(err)
							}
						});
					} else {
						resolve(files.filePath)
					}
				})
			)
		}
		Promise.all(taskResult).then((res) => {
			resolve(res)
		}).catch(() => {
			reject()
		})
	})

}


export default {
	env: env,
	toolsMethods: tools,
	systemInfo: uni.getSystemInfoSync(),
	getPolicyBase64: getPolicyBase64,
	getSignature: getSignature,
	getFileInfo: getFileInfo,
	formatFiles: formatFiles,
	uploadFiles: uploadFiles,
};